package org.dromara.bclt.websocket.service.impl;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.bclt.websocket.constant.ChatConstants;
import org.dromara.bclt.websocket.domain.ChatMessage;
import org.dromara.bclt.websocket.mapper.ChatMapper;
import org.dromara.bclt.websocket.service.ChatService;
import org.dromara.common.core.utils.DateUtils;
import org.dromara.common.websocket.dto.WebSocketMessageDto;
import org.dromara.common.websocket.utils.WebSocketUtils;
import org.dromara.common.json.utils.JsonUtils;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * 聊天服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ChatServiceImpl implements ChatService {

    private final ChatMapper chatMapper;

    @Override
    public boolean sendMessage(ChatMessage chatMessage) {
        try {
            // 设置消息默认值
            if (chatMessage.getReadStatus() == null) {
                chatMessage.setReadStatus(ChatConstants.MESSAGE_STATUS_UNREAD);
            }
            if (chatMessage.getCreateTime() == null) {
                chatMessage.setCreateTime(DateUtils.getNowDate());
            }

            // 通过WebSocket发送消息到接收者
            WebSocketMessageDto webSocketMessageDto = new WebSocketMessageDto();
            webSocketMessageDto.setSessionKeys(Collections.singletonList(chatMessage.getReceiverId()));
            webSocketMessageDto.setMessage(JsonUtils.toJsonString(chatMessage));
            WebSocketUtils.publishMessage(webSocketMessageDto);

            // 保存消息到数据库
            int rows = chatMapper.insertChatMessage(chatMessage);

            return true;
        } catch (Exception e) {
            log.error("发送消息失败", e);
            return false;
        }
    }

    @Override
    public List<ChatMessage> getChatHistory(Long userId1, Long userId2, Integer limit) {
        return chatMapper.selectChatHistory(userId1, userId2, limit);
    }

    @Override
    public int markMessageAsRead(Long senderId, Long receiverId) {
        return chatMapper.updateMessageRead(senderId, receiverId, new Date());
    }

    @Override
    public int getUnreadMessageCount(Long receiverId) {
        return chatMapper.selectUnreadCount(receiverId);
    }
}
